﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessLogic;
using DataEntity;
using JScripter;
using BusinessLogic.Controller;

public partial class Admin_AjaxPages_StateAdd : AjaxPage
{
    private Guid ID
    {
        get
        {
            if (Request.Params["cid"] != null || AjaxState.ContainsKey("cid"))
            {
                if (!AjaxState.ContainsKey("cid"))
                    AjaxState["cid"] = Request.Params["cid"];
                return new Guid(AjaxState["cid"]);
            }
            else
            {
                return Guid.Empty;
            }
        }
    }


    protected override void OnLoad(EventArgs e)
    {
        if (ID != Guid.Empty)
        {
            BindData();
        }
        else
        {
            new CountryController().BindCountry(ddCountry);
        }
        base.OnLoad(e);
    }
    private void AddData()
    {
        try
        {
            State objState = new State();

            objState.StateID = Guid.NewGuid();

            objState.CountryId = Convert.ToInt32(HtmlHelper.ControlValue(ddCountry.ClientID));

            objState.Name = HtmlHelper.ControlValue(txtName.ClientID);

            objState.ModifiedDate = DateTime.Now;

            new StateController().Add(objState);
            Response.Redirect("~/Admin/AjaxPages/StateList.aspx");
        }
        catch (Exception ex)
        {
            divMessage.InnerHtml = "<div class='error'>" + ex.Message + "</div>";
        }
    }

    private void EditData()
    {

        State objState = new State();

        objState.StateID = ID;

        objState.CountryId = Convert.ToInt32(HtmlHelper.ControlValue(ddCountry.ClientID));

        objState.Name = HtmlHelper.ControlValue(txtName.ClientID);

        objState.ModifiedDate = DateTime.Now;

        new StateController().UpdateByStateID(objState);

        Response.Redirect("~/Admin/AjaxPages/StateList.aspx");
    }

    private void BindData()
    {
        var dataBunch = new StateController().GetbyStateID(ID);
        if (dataBunch.Count > 0)
        {
            var data = dataBunch[0];


            new CountryController().BindCountry(ddCountry, data.CountryId.ToString());
            

            txtName.Text = data.Name;

            

        }
    }

    protected void AddAjaxClick(object sender, AjaxControl.AjaxEventArg e)
    {
        AddData();

    }
    protected void UpdateAjaxClick(object sender, AjaxControl.AjaxEventArg e)
    {
        EditData();
    }
    public void PreventData()
    {

        txtName.Text = HtmlHelper.ControlValue(txtName.ClientID);
        

    }

}